from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from random import randint
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code
# from meiduo_mall.libs.yuntongxun.sms import CCP
# from threading import Thread
# Create your views here.

# def send_sms_code(mobile,sms_code):
#     # 4.发送短信验证码
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code,'5'],1)



class SMS_codeview(APIView):
    """
    发送短信
    """

    def get(self,request,mobile):
        # 判断发送间隔是否在60s内
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s'%mobile)
        """
        如果能获取到flag的值，说明在60s内，如果获取不到，说明已经过了60s，可以继续获取，flag数据过期，获取不到的化不会报错，会返回None值
        """
        if flag:
            # 说明在60s内
            return Response({'error':'请求过于频繁'},status=402)
        # 1.获取手机号
        # 2.生成短信验证码
        sms_code = '%06d'%randint(0,999999)
        # 3.在redis中保存真实短信验证码
        # 生成管道对象
        pl = conn.pipeline()
        pl.setex('sms_code_%s'%mobile, 300, sms_code)
        # conn.setex('sms_code_%s' % mobile, 300, sms_code)

        pl.setex('sms_code_flag_%s'%mobile,60,2)
        # conn.setex('sms_code_flag_%s' % mobile, 60, 2)
        # 调用下面的方法，链接redis，传递数据
        pl.execute()
        # 4.发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)# 5是五分钟有效期
        # t = Thread(target=send_sms_code,args=(mobile,sms_code))
        # t.start()
        # 4.celery调用 传递两个参数
        send_sms_code.delay(mobile, sms_code)
        # 5.结果返回
        return Response({'message':'OK'})








